package org.jkd.ams.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.jkd.ams.core.codec.MDRProtocolServerCodecFactory;

public class GenericAmServer {

	private static final String CODEC_FILTER_KEY = "codec";

	private String hostIpAddress;
	
	private int hostPort;

	private NioSocketAcceptor socketAcceptor;
	
	public GenericAmServer(String hostIpAddress, int hostPortAddress) {
		super();
		this.hostIpAddress = hostIpAddress;
		this.hostPort = hostPortAddress;
	}

	
	@PostConstruct
	public void start() throws IOException{
		
		socketAcceptor = new NioSocketAcceptor();
		socketAcceptor.getFilterChain().addLast(CODEC_FILTER_KEY, new ProtocolCodecFilter(new MDRProtocolServerCodecFactory()));
		socketAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		socketAcceptor.setHandler(new ServerSessionHandler());
		socketAcceptor.bind(new InetSocketAddress(hostIpAddress, hostPort));
		
		System.out.println("AM Server is Listening on " + hostIpAddress + ":" + hostPort);
	}
	
	@PreDestroy
	public void stop(){
		if(socketAcceptor != null){
			socketAcceptor.unbind();
			socketAcceptor.dispose();
		}
	}
}
